﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Browser;

namespace PrismNavigationFramework.Infrastructure
{
    public class SeparatedKeyValuePairsParsingService : IKeyValuePairsParsingService
    {
        public SeparatedKeyValuePairsParsingService()
        {
            this.Separator = "/";
            this.NumberOfItemsToSkip = 0;
        }

        public string Separator { get; set; }
        public int NumberOfItemsToSkip { get; set; }

        public string SerializeKeysAndValues(IDictionary<string, string> keysAndValues)
        {
            var sb = new StringBuilder();
            foreach (var keyValue in keysAndValues)
            {
                sb.AppendFormat("{0}{1}{2}{3}", keyValue.Key, this.Separator, keyValue.Value, this.Separator);
            }

            if (sb.Length > 1)
            {
                sb.Length = sb.Length - 1;
            }

            return sb.ToString();
        }

        public Dictionary<string, string> ExtractKeysAndValues(string rawData)
        {
            var result = new Dictionary<string, string>();

            if (string.IsNullOrEmpty(rawData))
            {
                return result;
            }
            else
            {
                rawData = rawData.Trim();
            }

            var parts = rawData.Split(new [] {this.Separator}, StringSplitOptions.RemoveEmptyEntries);

            if (this.NumberOfItemsToSkip > 0 && parts.Length <= this.NumberOfItemsToSkip)
            {
                return result;
            }

            var parametersNames = parts.Skip(this.NumberOfItemsToSkip);
            var values = parts.Skip(this.NumberOfItemsToSkip + 1);

            while (parametersNames.Any())
            {
                var value = values.Take(1).FirstOrDefault();
                var urlDecodedValue = HttpUtility.UrlDecode(value);
                result.Add(parametersNames.Take(1).First(), urlDecodedValue);
                parametersNames = parametersNames.Skip(2);
                values = values.Skip(2);
            }

            return result;
        }
    }
}